﻿// Copyright 2009 Mike Geise
// 
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
// 
//     http://www.apache.org/licenses/LICENSE-2.0
// 
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

namespace Falcon.Core.Controllers
{
	using System.Web.Mvc;
	using Falcon.Core.Domain;
	using Falcon.Core.Domain.Enums;
	using Falcon.Core.Domain.Extensions;
	using Falcon.Core.Domain.Services;
	using Falcon.Core.Domain.Values;
	using Falcon.Core.Extensions;
	using Falcon.Core.Validation;

	public class UserSearchController : DefaultController
	{
		public UserSearchController(IUserSearchService userSearchService)
		{
			this.UserSearchService = userSearchService;
		}

		public IUserSearchService UserSearchService
		{
			get;
			private set;
		}

		[AcceptVerbs(HttpVerbs.Get)]
		public ActionResult Index(int id, int? page)
		{
			var results = UserSearchService.GetPaged(new UserSearchSpecification
			{
				Id = id,
				Page = page,
				Limit = Settings.Users.PageLimit
			});

			UserSearchService.DeleteExpired();

			return View(Views.Index, results);
		}

		[AcceptVerbs(HttpVerbs.Get)]
		public ActionResult Create()
		{
			return View(Views.Create, Masters.System, new UserSearchCreate());
		}

		[AcceptVerbs(HttpVerbs.Post)]
		public ActionResult Create(UserSearchCreate value)
		{
			try
			{
				var search = UserSearchService.Create();

				UserSearchService.Insert(search, value);
				UserSearchService.DeleteExpired();

				return RedirectToRoute(Routes.UserSearchIndex, new { id = search.Id, page = 1 });
			}
			catch (ValidationException exception)
			{
				ModelState.CopyValidationExceptions(exception);
			}

			return View(Views.Create, value);
		}

		[AcceptVerbs(HttpVerbs.Get)]
		public ActionResult Lookup(string s, string q, int limit)
		{
			UserSearchService.DeleteExpired();

			var search = UserSearchService.Create();

			var scope = s.AsEnum<UserSearchScope>();

			search.QueryBasedOnScope(scope, q);

			UserSearchService.Insert(search);

			var results = UserSearchService.GetPaged(new UserSearchSpecification
			{
				Id = search.Id,
				Scope = scope,
				Page = 1,
				Limit = limit
			});

			return Text(results.AsText());
		}
	}
}